package com.lagou.edu.service;

import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.model.AuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

/**
 * 验证码业务层接口服务
 */
@Service
public class AuthCodeService implements IAuthCodeService {

    @Autowired
    private AuthCodeDao authCodeDao;

    @Override
    public AuthCode findListByCondition(AuthCode authCodeSearch) {
        Example<AuthCode> example = Example.of(authCodeSearch);
        List<AuthCode> list = authCodeDao.findAll(example);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

    @Override
    public AuthCode saveAuthCode(String email) {
        AuthCode authCode = new AuthCode();

        //设置通用属性
        authCode.setEmail(email);
        AuthCode authCodeDb = findListByCondition(authCode);
        authCode.setCreatetime(new Date());
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime expire = localDateTime.plusMinutes(5l);
        authCode.setExpiretime(Date.from(expire.atZone(ZoneId.systemDefault()).toInstant()));

        //设置验证码
        authCode.setCode(getAuthCode());

        if(authCodeDb !=null){
            authCode.setId(authCodeDb.getId());
        }
        return authCodeDao.saveAndFlush(authCode);
    }

    private String getAuthCode(){
        StringBuffer authCode = new StringBuffer();
        for(int i=0;i<6;i++){
            SecureRandom secureRandom = new SecureRandom();
            authCode.append(secureRandom.nextInt(10));
        }
        return authCode.toString();
    }


}
